package views

import (
	"fmt"
	"github.com/charmbracelet/bubbles/table"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

type model struct {
	table   table.Model
	Columns []table.Column
	Rows    []table.Row
}

func NewTable() model {

	t := table.New(
		table.WithColumns([]table.Column{
			{
				Title: "1",
				Width: 10,
			},
			{
				Title: "2",
				Width: 10,
			},
			{
				Title: "3",
				Width: 11,
			},
		}),
		table.WithRows([]table.Row{}),
		table.WithFocused(true),
		table.WithHeight(7),
	)
	s := table.DefaultStyles()
	s.Header = s.Header.
		BorderStyle(lipgloss.NormalBorder()).
		BorderForeground(lipgloss.Color("240")).
		BorderBottom(true).
		Bold(false)
	s.Selected = s.Selected.
		Foreground(lipgloss.Color("229")).
		Background(lipgloss.Color("57")).
		Bold(false)
	t.SetStyles(s)

	t.SetRows([]table.Row{
		{"1", "2", "3"},
	})
	t.SetColumns([]table.Column{
		{
			Title: "1",
			Width: 10,
		},
		{
			Title: "2",
			Width: 10,
		},
		{
			Title: "3",
			Width: 11,
		},
	})
	return model{
		table: t,
	}
}

var baseStyle = lipgloss.NewStyle().
	BorderStyle(lipgloss.NormalBorder()).
	BorderForeground(lipgloss.Color("240"))

func (m model) Init() tea.Cmd { return nil }

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmd tea.Cmd
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "r":
			m.table.SetColumns(m.Columns)
			m.table.SetRows(m.Rows)
			return m, nil
		case "esc":
			if m.table.Focused() {
				m.table.Blur()
			} else {
				m.table.Focus()
			}

		case "4l":
			fmt.Println("4l")
			return m, nil
		case "q", "ctrl+c":
			return m, tea.Quit
		case "enter":
			return m, tea.Batch(
				tea.Printf("Let's go to %s!", m.table.SelectedRow()[1]),
			)
		}
	}
	m.table, cmd = m.table.Update(msg)
	return m, cmd
}

func (m model) View() string {
	return baseStyle.Render(m.table.View()) + "\n"
}
